/*
 * @author: wizardc
 */

using UnityEngine;

namespace Dou.UI
{
    /// <summary>
    /// UI元素跟随场景元素
    /// </summary>
    public class UIFollowTarget : MonoBehaviour
    {
        /// <summary>
        /// UI 摄像机
        /// </summary>
        public Camera uiCamera;

        /// <summary>
        /// 跟随目标的摄像机
        /// </summary>
        public Camera followTargetCamera;

        /// <summary>
        /// 跟随目标
        /// </summary>
        public Transform target;

        /// <summary>
        /// 跟随目标偏移
        /// </summary>
        public Vector3 offset = Vector3.zero;

        void Update()
        {
            RectTransform rectTransform = transform as RectTransform;
            if (rectTransform != null)
            {
                Vector2 pos = RectTransformUtility.WorldToScreenPoint(followTargetCamera, target.position + offset);
                RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, pos, uiCamera,
                    out Vector3 worldPoint);
                rectTransform.position = worldPoint;
            }
            else
            {
                Vector3 pos = followTargetCamera.WorldToScreenPoint(target.position + offset);
                transform.position = uiCamera.ScreenToWorldPoint(pos);
            }
        }
    }
}
